package mo.leetcode_top;

import java.util.LinkedList;
import java.util.Queue;

public class L130 {

    public void solve(char[][] board) {
        int x = board.length;
        int y = board[0].length;

        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (i != 0 && i != x-1 && j != 0 && j != y-1) {
                    continue;
                }
                if (board[i][j] != 'O') {
                    continue;
                }
                board[i][j] = '$';
                //转换成int值，根据原来的x,y转换
                int convert = i * y + j;
                LinkedList<Integer> nodes = new LinkedList<>();
                nodes.add(convert);
                while (!nodes.isEmpty()) {
                    Integer value = nodes.pollFirst();
                    int m = value / y;
                    int n = value % y;
                    if (m >= 1 && board[m-1][n] == 'O') {
                        board[m-1][n] = '$';
                        nodes.offer(value-y);
                    }
                    if (m < x-1 && board[m+1][n] == 'O') {
                        board[m+1][n] = '$';
                        nodes.offer(value+y);
                    }
                    if (n >= 1 && board[m][n-1] == 'O') {
                        board[m][n-1] = '$';
                        nodes.offer(value-1);
                    }
                    if (n < y-1 && board[m][n+1] == 'O') {
                        board[m][n+1] = '$';
                        nodes.offer(value+1);
                    }
                }
            }
        }

        for (int i = 0; i < x; i++) {
            for (int j = 0; j <y ; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
                if (board[i][j] == '$') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    public static void main(String[] args) {
        L130 test = new L130();
        char[][] board = new char[][]{{'O','O','O','O','O','O'},{'O','X','X','X','X','O'},{'O','X','O','O','X','O'},{'O','X','O','O','X','O'},{'O','X','X','X','X','O'},{'O','O','O','O','O','O'}};
        test.solve(board);
        System.out.println(board);
    }

}
